package dk.sdu.flexibus.communications;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;

public class GetPickupInformationProvider extends
		AbstractCommunicationsProvider {

	private int serverId;
	private GetPickupInformationListener listener;

	public GetPickupInformationProvider(int serverId,
			GetPickupInformationListener listener) {
		this.serverId = serverId;
		this.listener = listener;
	}
	
	@Override
	protected void composeMessage(SoapObject request) {
		request.addProperty("transportID", serverId);
	}

	@Override
	protected String getMethodName() {
		return "GetPickupInformation";
	}

	@Override
	protected String getSoapAction() {
		return "http://www.madis.dk/Uni/FlexiBus/GetPickupInformation";
	}

	@Override
	protected CallServiceTask getCallServiceTask() {
		return new GetPickupInformationCallTask();
	}

	@Override
	protected boolean getDebugSetting() {
		return true;
	}
	
	private class GetPickupInformationCallTask extends CallServiceTask {

		@Override
		protected void onPostExecute(SoapSerializationEnvelope envelope) {
			try {
				SoapObject response = (SoapObject) envelope.getResponse();
				String errorCodeString = ((SoapPrimitive) response.getProperty("ErrorCode")).toString();
				String transportIDString = ((SoapPrimitive) response.getProperty("TransportID")).toString();
				String pickUpString = ((SoapPrimitive) response.getProperty("PickUp")).toString();
				Calendar pickUpTime = new GregorianCalendar();
				
				if(errorCodeString.equals("None")){
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
					//2012-12-11T12:33:39
					pickUpTime.setTime(format.parse(pickUpString));
				}
				int transportID = Integer.parseInt(transportIDString);
				listener.sendPickupInformation(errorCodeString, pickUpTime, transportID);
			} catch (Exception exception) {
				listener.sendError(exception);
			}
		}
	}

}
